<template>
  <view class="recharge-warp">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="充值"></van-nav-bar>
    <!-- #endif -->
    <view class="recharge-warp-cnt" :style="heightScroll">
      <view class="coupon-content">
        <text class="title text-bold">充值金额</text>
        <view class="recharge-info">
          <template v-if="appType === 'lznt'">
            <view
              class="oneFloor"
              v-for="(item, index) in data.moneyList"
              :key="index"
              :class="item.isChecked ? 'is_checked' : 'no_checked'"
              @tap="Select(item.id, index)">
              <text :class="item.isChecked ? 'is_checkedText' : ''">￥{{ item.id }}</text>
            </view>
          </template>
          <template v-else>
            <view
              class="oneFloor"
              v-for="(item, index) in data.moneyList1"
              :key="index"
              :class="item.isChecked ? 'is_checked' : 'no_checked'"
              @tap="Select(item.id, index)">
              <text :class="item.isChecked ? 'is_checkedText' : ''">￥{{ item.id }}</text>
            </view>
          </template>
        </view>
        <view class="contain-detail">
          <input
            class="content-input"
            :class="{ 'input-select': data.isInput }"
            type="digit"
            maxlength="8"
            v-model="data.money"
            placeholder="请输入其他金额"
            @focus="focusInput" />
        </view>
      </view>
      <view class="coupon-activity" v-if="data.hasActivity">
        <view class="coupon-activity-banner">
          <view class="icon"></view>
          <view class="des">充值送活动</view>
        </view>
        <view class="coupon-activity-list">
          <view class="title">当前平台有如下充值活动，您可选择参与？</view>
          <view class="ul">
            <view
              v-for="(item, index) in data.activityTypes"
              :class="['li', index === data.activityIndex ? 'li-active' : '']"
              :key="index"
              @tap="changeActivity(index)">
              活动{{ toChinesNum(index + 1) }}
            </view>
          </view>
          <view class="line"></view>
          <view class="des des-red">
            同一用户最多可参与{{ data.activityTypes[data.activityIndex]?.participatingCount }}次！
          </view>
          <view class="des">
            <view class="des-li" v-for="(ruleItem, index) in ruleList" :key="index">
              {{ ruleItem }}
            </view>
          </view>
        </view>
      </view>
      <view class="bottom-wrap">
        <view v-if="data.hasActivity">
          <view class="coupon-activity-agree" @tap="tapAgreement">
            <view class="radio-wrap" :class="{ 'radio-radius': !checkAgreement }">
              <icon v-if="checkAgreement" :type="'success'" :color="colors.systemColor" size="16" />
            </view>
            <text>同意参与当前活动</text>
          </view>
          <view class="coupon-activity-notice">
            注：参与活动对应的充值金额仅用于充电消费，不支持退款！
          </view>
        </view>
        <button class="bnt-wrap bnt" @tap="recharge">充值</button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import {
  colors,
  getSystemInfo,
  getUserId,
  getOpenId,
  systemInfo,
  getwv,
  setToastInstance,
} from '@mixins/info';
import { unifiedOrder, checkUnifiedOrder } from '@/service/apis/mine';
import { queryUserActivity } from '@/service/apis/market';
import { noMultipleClicks } from '@/utils/util';
import { mathMultiplys } from '@/utils/maths';
// #ifdef H5
import nativeApi from '@/mixins/nativeApi';
// #endif
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const appType = import.meta.env.VITE_VUE_APP_TYPE;
const originId = import.meta.env.VITE_VUE_APP_ORIGIN_ID;
const miniEnv = import.meta.env.VITE_VUE_APP_MINI_ENV;

const $toast: any = inject('$Toast');

const heightScroll = computed(() => {
  if (data.hasActivity) {
    // #ifdef H5
    return `height: ${
      systemInfo.screenHeight - getwv(128) - systemInfo.safeBottom - systemInfo.navHeight
    }px`;
    // #endif
    return `height: ${systemInfo.screenHeight - getwv(128) - systemInfo.safeBottom}px`;
  }
  // #ifdef H5
  return `height: ${
    systemInfo.screenHeight - getwv(62) - systemInfo.safeBottom - systemInfo.navHeight
  }px`;
  // #endif
  return `height: ${systemInfo.screenHeight - getwv(62) - systemInfo.safeBottom}px`;
});

let checkAgreement = ref(false); //是否勾选同意活动充值

const data = reactive({
  hasActivity: false,
  activityIndex: 0,
  activityTypes: [] as any[],
  isChecked1: false,
  isChecked2: true,
  isChecked3: false,
  isChecked4: false,
  isChecked5: false,
  isChecked6: false,
  isInput: false,
  rechargeMoney: 0,
  money: '',
  moneyList: [
    {
      isChecked: true,
      id: 5,
    },
    {
      isChecked: false,
      id: 10,
    },
    {
      isChecked: false,
      id: 20,
    },
    {
      isChecked: false,
      id: 50,
    },
    {
      isChecked: false,
      id: 100,
    },
    {
      isChecked: false,
      id: 200,
    },
  ],
  moneyList1: [
    {
      isChecked: true,
      id: 10,
    },
    {
      isChecked: false,
      id: 50,
    },
    {
      isChecked: false,
      id: 100,
    },
    {
      isChecked: false,
      id: 200,
    },
    {
      isChecked: false,
      id: 500,
    },
    {
      isChecked: false,
      id: 1000,
    },
  ],
});

const ruleList = computed(() => {
  return data.activityTypes[data.activityIndex]?.rule.split('|').slice(0, -1) || [];
});

onLoad((option: any) => {
  console.log('option=====', option);
  getRechargeActivity();
  if (appType === 'lznt') {
    data.rechargeMoney = 5;
  } else {
    data.rechargeMoney = 10;
  }
  recharge = noMultipleClicks(recharge);
});

// 查询活动充值
const getRechargeActivity = () => {
  queryUserActivity({
    type: 2, // 活动类型 1:注册活动 2:充值活动 3:首次充电活动 4:组团充电活动 5:单次消费活动 6:累计消费活动 7:分享活动 8:扫码领券活动
    status: 1, // 活动状态 0:未开始 1:进行中 2:结束 3:终止(手动) 4:终止(自动)
  }).then(res => {
    if (Array.isArray(res) && res.length > 0) {
      data.hasActivity = true;
      data.activityTypes = res;
    }
  });
};

// 同意活动充值
const tapAgreement = () => {
  checkAgreement.value = !checkAgreement.value;
};

const changeActivity = (index: number) => {
  data.activityIndex = index;
};

// #ifdef H5
const openWxFromH5 = (money: any) => {
  let path = `pages/appPay/appPay?userId=${getUserId()}&payValue=${money}`;
  if (checkAgreement.value) {
    path = `pages/appPay/appPay?userId=${getUserId()}&payValue=${money}&activityId=${
      data.activityTypes[data.activityIndex]?.id
    }`;
  }
  nativeApi
    .navigateToMiniProgram({
      appletId: originId,
      path,
      env: miniEnv, // develop  preview  publish
    })
    .then((res: any) => {
      console.log('res', res);
    })
    .catch(() => {
      $toast('支付失败');
    });
};
// #endif

let recharge = () => {
  if ((!data.money || Number(data.money) === 0) && Number(data.rechargeMoney) === 0) {
    $toast('请选择或输入金额,充值金额要大于0');
    return;
  }
  if (data.money) {
    if (!new RegExp(/^\d+(\.\d{1,2})?$/).test(data.money)) {
      $toast('请输入正确的金额');
      return;
    }
    if (Number(data.money) > 10 * 10000) {
      $toast('请输入小于10万的金额');
      return;
    }
  }
  const money = data.money ? Number(data.money) : data.rechargeMoney;
  const moneyVal = mathMultiplys(money, 100);
  console.log('222-----', money, moneyVal);
  // #ifdef MP-WEIXIN
  const obj: any = {
    userId: getUserId(),
    source: 0,
    totalMoney: moneyVal,
    openId: getOpenId(),
  };
  console.log('obj-----', obj);
  if (checkAgreement.value) {
    obj.activityId = data.activityTypes[data.activityIndex]?.id;
  }

  unifiedOrder(obj).then((res: any) => {
    uni.requestPayment({
      orderInfo: '',
      provider: 'wxpay',
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      package: res.packageVal,
      signType: res.signType,
      paySign: res.paySign,
      success: (pay: any) => {
        console.log('success:' + JSON.stringify(pay));
        $toast('支付操作成功');
        uni.navigateBack();
      },
      fail: (err: any) => {
        console.log('fail:' + JSON.stringify(err));
        $toast('支付操作失败');
      },
    });
  });
  // #endif

  // #ifdef H5
  if (checkAgreement.value) {
    checkUnifiedOrder({
      activityId: data.activityTypes[data.activityIndex]?.id,
      totalMoney: mathMultiplys(money, 100),
    }).then(() => {
      openWxFromH5(money);
    });
  } else {
    openWxFromH5(money);
  }
  // #endif
};
const flagCheck = () => {
  data.isChecked1 = false;
  data.isChecked2 = false;
  data.isChecked3 = false;
  data.isChecked4 = false;
  data.isChecked5 = false;
  data.isChecked6 = false;
};
const Select = (e: any, index: any) => {
  data.money = '';
  data.isInput = false;
  flagCheck();
  data.moneyList.map((item, ind) => {
    if (appType === 'lznt') {
      if (ind == index) {
        data.moneyList[index].isChecked = true;
      } else {
        data.moneyList[ind].isChecked = false;
      }
    } else {
      if (ind == index) {
        data.moneyList1[index].isChecked = true;
      } else {
        data.moneyList1[ind].isChecked = false;
      }
    }
  });
  data.rechargeMoney = e;
};
const focusInput = () => {
  flagCheck();
  if (appType === 'lznt') {
    data.moneyList.map((item, ind) => {
      data.moneyList[ind].isChecked = false;
    });
  } else {
    data.moneyList1.map((item, ind) => {
      data.moneyList1[ind].isChecked = false;
    });
  }
  data.isInput = true;
  data.rechargeMoney = 0;
};

/**
 * 数字转成汉字
 * @params num === 要转换的数字
 * @return 汉字
 * */
const toChinesNum = (num: number | string) => {
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  let unit = ['', '十', '百', '千', '万'];
  num = parseInt(num as string);
  let getWan = (temp: any) => {
    let strArr = temp.toString().split('').reverse();
    let newNum = '';
    let newArr: any = [];
    strArr.forEach((item: any, index: number) => {
      newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index]);
    });
    let numArr: any = [];
    newArr.forEach((m: any, n: number) => {
      if (m !== '零') numArr.push(n);
    });
    if (newArr.length > 1) {
      newArr.forEach((m: any, n: number) => {
        if (newArr[newArr.length - 1] === '零') {
          if (n <= numArr[numArr.length - 1]) {
            newNum += m;
          }
        } else {
          newNum += m;
        }
      });
    } else {
      newNum = newArr[0];
    }

    return newNum;
  };
  let overWan = Math.floor(num / 10000);
  let noWan: number | string = num % 10000;
  if (noWan.toString().length < 4) {
    noWan = '0' + noWan;
  }
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
};

// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss" scoped>
.recharge-warp {
  position: relative;
  // height: 100vh;
  // height: calc(100vh - 62px - constant(safe-area-inset-bottom));
  // height: calc(100vh - 62px - env(safe-area-inset-bottom));
  // padding-top: 12px;
  background-color: #f2f2f2;
  // overflow-y: scroll;
  &-cnt {
    box-sizing: border-box;
    position: relative;
    padding-top: 12px;
    background-color: #f2f2f2;
    overflow-y: scroll;
  }

  .coupon-content {
    margin: 0 12px 16px 12px;
    padding: 16px;
    background-color: #fff;
    font-size: 14px;
    color: #545454;
    border-radius: 8px;

    &:last-child {
      border: 0;
    }

    .title {
      line-height: 24px;
      color: #000;
    }

    .recharge-info {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .oneFloor {
        width: 98px;
        height: 44px;
        line-height: 44px;
        font-size: 16px;
        font-weight: 600;
        text-align: center;
        margin-top: 12px;
        border: 1px solid #d5d5d5;
        border-radius: 8px;
      }

      .is_checkedText {
        color: $uni-color-primary;
      }

      .is_checked {
        border-color: $uni-color-primary;
        color: $uni-color-primary;
      }
    }

    .contain-detail {
      color: black;
      font-size: 14px;
      margin-top: 12px;
      display: flex;
      flex-flow: row;
      position: relative;
      align-items: center;

      .content-input {
        width: 318px;
        height: 44px;
        border: 1px solid #d5d5d5;
        border-radius: 8px;
        padding: 0 16px;

        &.input-select {
          border-color: $uni-color-primary;
        }
      }
    }

    .line {
      margin: 12px 0;
      height: 1px;
      background-color: #f2f2f2;
      // border-bottom: 1px solid #f2f2f2;
    }
  }

  .coupon-activity {
    margin: 0 12px;
    padding-bottom: 85px;
    // #ifdef H5
    padding-bottom: 20px;
    // #endif

    &-banner {
      display: flex;
      align-items: center;
      width: 351px;
      height: 44px;
      border-radius: 8px;
      background: #ffecec;
      margin-bottom: 16px;

      .icon {
        width: 80px;
        height: 80px;
        background-image: url($url + 'mine/recharge-icon.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        position: relative;
        top: -12px;
      }

      .des {
        padding-left: 7px;
        color: #fa3939;
        font-size: 16px;
        font-weight: 500;
        line-height: 22px;
      }
    }

    &-list {
      box-sizing: border-box;
      padding: 16px;
      border-radius: 8px;
      background: #fff;

      .title {
        color: #242424;
        font-size: 16px;
        font-weight: 500;
        line-height: 24px;
        padding-bottom: 16px;
      }

      .ul {
        display: flex;
        width: 100%;
        height: 36px;
        overflow-x: scroll;

        &::-webkit-scrollbar {
          display: none;
        }

        .li {
          box-sizing: border-box;
          height: 36px;
          padding: 8px 24px;
          border-radius: 8px;
          background-color: #f2f2f2;
          color: #545454;
          margin-right: 23px;
          white-space: nowrap;

          &:last-child {
            margin-right: 0;
          }
        }

        .li-active {
          background-color: #fa3939;
          color: #ffffff;
        }
      }

      .line {
        margin-top: 16px;
        padding-bottom: 11px;
        width: 316px;
        border-top: 1px solid #e6e6e6;
      }

      .des {
        color: #545454;
        font-size: 14px;
        line-height: 24px;

        &-red {
          color: #fa3939;
        }

        &-li {
          position: relative;
          padding-left: 20px;
          margin-bottom: 5px;

          &::before {
            content: '';
            position: absolute;
            top: 10px;
            left: 6px;
            background-color: #000;
            width: 5px;
            height: 5px;
            border-radius: 50%;
          }
        }
      }
    }
  }

  .bottom-wrap {
    // display: flex;
    position: fixed;
    width: 100%;
    // height: calc(62px + constant(safe-area-inset-bottom));
    // height: calc(62px + env(safe-area-inset-bottom));
    padding-bottom: calc(9px + constant(safe-area-inset-bottom));
    padding-bottom: calc(9px + env(safe-area-inset-bottom));
    bottom: 0;
    background: #fff;
    border-top: 1px solid #e6e6e6;
    box-sizing: border-box;

    .coupon-activity-agree {
      margin-top: 12px;
      padding-left: 15px;
      display: flex;
      align-items: center;

      .radio-wrap {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }

      .radio-radius {
        border: 1px solid $uni-color-primary;
        border-radius: 50%;
        box-sizing: border-box;
      }

      text {
        line-height: 22px;
        font-size: 14px;
        color: $uni-color-primary;
      }
    }

    .coupon-activity-notice {
      color: #fa3939;
      font-size: 11px;
      line-height: 24px;
      margin-bottom: 16px;
      padding-left: 15px;
    }

    .bnt {
      height: 44px;
      width: 343px;
      margin-top: 9px;
      border-radius: 50px;
    }
  }
}
</style>